package org.akomantoso.core.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.akomantoso.core.data.attribute.Source;
import org.akomantoso.core.io.Externalizable;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.Output;
import org.akomantoso.core.io.OutputUtil;

/**
 * <pre>
 * <xsd:element name="lifecycle">
 * 		<xsd:complexType>
 * 			<xsd:sequence>
 * 				<xsd:element ref="eventRef" minOccurs="1" maxOccurs="unbounded"/>
 *			</xsd:sequence>
 * 			<xsd:attributeGroup ref="source"/>
 *		</xsd:complexType>
 * </xsd:element>
 * </pre>
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public final class Lifecycle implements Source, Externalizable {

	public static final String ELEMENT = "lifecycle";
	
	// mandatory (min 1)
	private final List<EventRef> _eventRefs = new ArrayList<EventRef>();

	// optional
	private String _source;
	
	/**
	 * @see org.akomantoso.core.data.attribute.Source#getSource()
	 */
	public String getSource() {
		return _source;
	}

	/**
	 * @see org.akomantoso.core.data.attribute.Source#setSource(java.lang.String)
	 */
	public void setSource(String source) {
		_source = source;
	}

	public List<EventRef> getEventRefs() {
		return _eventRefs;
	}

	public void addEventRef(EventRef ref) {
		_eventRefs.add(ref);
	}


	/**
	 * @see org.akomantoso.core.io.Externalizable#writeExternal(org.akomantoso.core.io.Output)
	 */
	public <T extends Output> void writeExternal(T out) throws IOException {
		out.writeStart(ELEMENT);
		OutputUtil.writeSource(out, this);
		for (EventRef ref : _eventRefs) {
			ref.writeExternal(out);
		}
		out.writeEnd();
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#readExternal(org.akomantoso.core.io.Input)
	 */
	public <T extends Input> void readExternal(T in) throws IOException {
		_source = in.readAttribute(Source.ATTRIBUTE);
		
		in.readNextStartElement();
		
		if (EventRef.ELEMENT.equals(in.getLocalName())) {
			EventRef eventRef;
			while (EventRef.ELEMENT.equals(in.getLocalName())) {
				_eventRefs.add(eventRef = new EventRef());
				eventRef.readExternal(in);
				in.readNextStartElement();
			}
		}
	}
	
}